<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发件邮箱" prop="sendFrom">
        <el-input
          v-model="queryParams.sendFrom"
          placeholder="请输入发件邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="sendUsername">
        <el-input
          v-model="queryParams.sendUsername"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否激活" prop="isActive">
        <el-select v-model="queryParams.isActive" placeholder="请选择是否激活" clearable>
          <el-option
            v-for="dict in isClosedOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['eduManage:config:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['eduManage:config:edit']"
        >修改</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="SMTP主机" align="center" prop="smtpHost" />
      <el-table-column label="SMTP端口" align="center" prop="smtpPort" />
      <el-table-column label="发件邮箱" align="center" prop="sendFrom" />
      <el-table-column label="用户名" align="center" prop="sendUsername" />
      <el-table-column label="邮箱授权码" align="center" prop="sendVerifyCode" />
      <el-table-column label="是否激活" align="center" prop="isActiveName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['eduManage:config:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['eduManage:config:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改系统邮箱配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="SMTP主机" prop="smtpHost">
          <el-input v-model="form.smtpHost" placeholder="不可修改" disabled />
        </el-form-item>
        <el-form-item label="SMTP端口" prop="smtpPort">
          <el-input v-model="form.smtpPort" placeholder="不可修改" disabled />
        </el-form-item>
        <el-form-item label="发件邮箱" prop="sendFrom">
          <el-input v-model="form.sendFrom" placeholder="请输入发件邮箱" />
        </el-form-item>
        <el-form-item label="用户名" prop="sendUsername">
          <el-input v-model="form.sendUsername" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱授权码" prop="sendVerifyCode">
          <el-input v-model="form.sendVerifyCode" placeholder="请输入邮箱授权码" />
        </el-form-item>
        <el-form-item label="是否激活" prop="isActive">
          <el-select v-model="form.isActive" placeholder="请选择是否激活" clearable>
            <el-option
              v-for="dict in isClosedOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="String(dict.dictValue)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConfig, getConfig, delConfig, addConfig, updateConfig } from "@/api/manage/config"
import { getDicts } from "@/api/system/dict/data"

export default {
  name: "Config",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 系统邮箱配置表格数据
      configList: [],
      // 是否激活字典选项
      isClosedOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        smtpHost: null,
        smtpPort: null,
        sendFrom: null,
        sendUsername: null,
        sendVerifyCode: null,
        isActive: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        smtpHost: [
          { required: true, message: "SMTP主机不能为空", trigger: "blur" }
        ],
        smtpPort: [
          { required: true, message: "SMTP端口不能为空", trigger: "blur" }
        ],
        sendFrom: [
          { required: true, message: "发件邮箱不能为空", trigger: "blur" }
        ],
        sendUsername: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        sendVerifyCode: [
          { required: true, message: "邮箱授权码不能为空", trigger: "blur" }
        ],
        isActive: [
          { required: true, message: "是否激活不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList();
    this.getDicts("yes_or_no").then(response => {
      this.isClosedOptions = response.data
    })
  },
  methods: {
    /** 查询系统邮箱配置列表 */
    getList() {
      this.loading = true
      listConfig(this.queryParams).then(response => {
        this.configList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        smtpHost: null,
        smtpPort: null,
        sendFrom: null,
        sendUsername: null,
        sendVerifyCode: null,
        isActive: null,
        remark: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 设置新增默认值（不可修改）
      this.form.smtpHost = 'smtp.qq.com'
      this.form.smtpPort = '465'
      this.open = true
      this.title = "添加系统邮箱配置"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getConfig(id).then(response => {
        this.form = response.data
        // 规范下拉回显：统一为字符串类型，并在缺失编码时用名称映射
        const mapActiveByName = () => {
          if ((this.form.isActive === null || this.form.isActive === undefined) && this.form.isActiveName) {
            const label = String(this.form.isActiveName).trim()
            const match = this.isClosedOptions.find(opt => String(opt.dictLabel).trim() === label)
            if (match) {
              this.form.isActive = String(match.dictValue)
            }
          }
        }
        if (this.form.isActive !== null && this.form.isActive !== undefined) {
          this.form.isActive = String(this.form.isActive)
        } else {
          // 如果字典选项尚未加载，先加载后映射
          if (!this.isClosedOptions || this.isClosedOptions.length === 0) {
            this.getDicts("yes_or_no").then(r => {
              this.isClosedOptions = r.data
              mapActiveByName()
            })
          } else {
            mapActiveByName()
          }
        }
        this.open = true
        this.title = "修改系统邮箱配置"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除系统邮箱配置编号为"' + ids + '"的数据项？').then(function() {
        return delConfig(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('eduManage/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
